import { createRouter, createWebHistory } from 'vue-router'
// 1. 重新引入 defineAsyncComponent（之前去掉是错误的）
import { defineAsyncComponent } from 'vue'
import { useUserStore } from '@/store/modules/user/user.js'
import BaseLoading from '../components/loading/BaseLoading.vue'
import ErrorComponent from '../components/loading/ErrorComponent.vue'

// 1. 用 import.meta.glob 批量导入 views 下所有 .vue 组件（支持多级目录）
// 说明：
// - ../views/**/*.vue：匹配 views 下所有子目录的 .vue 文件
// - { eager: false }：保持懒加载（默认就是 false，可省略）
const asyncComponents = import.meta.glob('../views/**/*.vue')

// 2. 重写异步组件加载函数（兼容 Vite 动态导入规则）
const loadAsyncComponent = (componentPath) => {
  const componentKey = `../views/${componentPath}.vue`
  const componentLoader = asyncComponents[componentKey]

  if (!componentLoader) {
    console.error(`未找到组件：${componentKey}`)
    return ErrorComponent
  }

  const routes = [
    // 注意：componentPath 格式不变（仍为 "home/Home" 这种多级路径），内部会通过 glob 匹配
    { path: '/home', component: loadAsyncComponent('home/Home'), alias: '/' },
    {
      path: '/message', component: loadAsyncComponent('message/Message'),
      children: [
        { path: 'followers', component: loadAsyncComponent('message/FollowersPage') },
        { path: 'likes', component: loadAsyncComponent('message/LikesPage') },
        { path: 'mentions', component: loadAsyncComponent('message/MentionsPage') },
        { path: 'comments', component: loadAsyncComponent('message/CommentsPage') },
      ]
    },
    { path: '/video', component: loadAsyncComponent('video/Video') },
    {
      path: '/user', component: loadAsyncComponent('user/User'),
      children: [
        { path: 'follows', component: loadAsyncComponent('user/MyFollowsPage') },
        { path: 'fans', component: loadAsyncComponent('user/MyFansPage') },
      ]
    },
    { path: '/follow', component: loadAsyncComponent('follow/Follow') },
    {
      path: '/search', component: loadAsyncComponent('search/search'),
      children: [
        { path: 'video', alias: '', component: loadAsyncComponent('search/VideoSearch') },
        { path: 'user', component: loadAsyncComponent('search/UserSearch') },
      ]
    },
    { path: '/profile/:userId', component: loadAsyncComponent('home/profile') },
    { path: '/contact-picker', component: loadAsyncComponent('ContactPicker/ContactPicker') },
    { path: '/ChatWith', component: loadAsyncComponent('ChatWith/ChatWith') },
  ]

  const router = createRouter({
    history: createWebHistory(),
    routes
  })

  const whiteList = ['/home', '/']

  router.beforeEach(async (to, from, next) => {
    if (whiteList.includes(to.path)) {
      next()
      return
    }
    const userStore = useUserStore()
    const isLogin = await userStore.checkLogin()
    if (isLogin) {
      next()
    } else {
      userStore.showLogin()
      next(false)
    }
  })

  export default router